package com.wechat.mp.controller;

import com.wechat.mp.config.WxMpProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@AllArgsConstructor
@Controller
@Slf4j
@RequestMapping("/wx")
public class WxShareController {
    private final WxMpService wxService;
    @Autowired
    WxMpProperties wxMpProperties;

    /**
     * 网页授权
     * @param code
     * @param model
     * @return
     */
    @RequestMapping("/webOauth2")
    public String webOauth2(String code, Model model) {
        System.out.println(code);
        //通过code换取access_token的票据每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
        try {
            if(StringUtils.isNotBlank(code)){
                WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxService.oauth2getAccessToken(code);
                System.out.println(wxMpOAuth2AccessToken.getAccessToken());
                //通过access_token和openid拉取用户信息
                WxMpUser wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, "");
                System.out.println(wxMpUser.getNickname());
                model.addAttribute("nickname",wxMpUser.getNickname());
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "webOauth2";
    }

    /**
     * 分享好友
     * @return
     */
    @RequestMapping("/sharepy")
    public String sharepy(String code, Model model) {
        try {
//            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
//            String ticket = HttpUtil.sendGet(url, "access_token=" + wxService.getAccessToken() + "&type=jsapi", "UTF-8");
//            System.out.println("得到ticket："+ticket);
            WxJsapiSignature jsapiSignature = wxService.createJsapiSignature(wxMpProperties.getBaseurl()+"/wx/sharepy");
            log.info("得到签名信息："+jsapiSignature);
            model.addAttribute("signature",jsapiSignature);
            model.addAttribute("baseurl",wxMpProperties.getBaseurl());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "share";
    }

    @RequestMapping("/success")
    public String success(String code, Model model) {
        return "success";
    }

}
